package com.miui.systemui.tools;

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.ui.Messages
import java.awt.Toolkit
import javax.swing.SwingUtilities


class Xml2JavaAction : AnAction() {

    @Volatile
    var isRequest = false;
    val dialog = Xml2JavaDialog()

    override fun actionPerformed(e: AnActionEvent) {
        // 获取当前打开的 XML 文件
        if (e.project == null) {
            Messages.showErrorDialog("No active project found", "Error")
            return
        }

        // 获取当前编辑的文件
        val currentFile = FileEditorManager.getInstance(e.project!!).selectedFiles[0]
        if (currentFile == null) {
            Messages.showErrorDialog("No active file found", "Error")
            return
        }

        if (isRequest) {
            Messages.showErrorDialog("当前正运行,请等待", "Error")
            return
        }
        val fileContent = String(currentFile.contentsToByteArray(), currentFile.charset)
        println("fileContent: " + fileContent)
        dialog.setLoadText()
        dialog.showDialog()
        Thread(object : Runnable {
            override fun run() {
                AiModel.requestAi(prompt = Prompt.promptSystem2,
                    fileContent,
                    success = { data: String ->
                        println("data:" + data)
                        if ("[DONE]".equals(data)) {
                            isRequest = false
                            return@requestAi
                        }
                        dialog.updateTextArea(data)
                    },
                    fail = { error: String ->
                        isRequest = false
                        println("error:" + error)
                        dialog.updateTextArea(error)
                    })
            }
        }).start()
    }

}

